﻿namespace SvCore.CmdLine;

public partial class SvCmd
{
    public Dictionary<string, CoreCmdAction> DictCmdAction = new Dictionary<string, CoreCmdAction>();
    public void AddController<T>(T t)
    {
        if (t == null)
        {
            return;
        }
        Type type = t.GetType();
        var methods = type.GetMethods();
        foreach (var method in methods)
        {
            var atts = method.GetCustomAttributes(typeof(CoreCmdAttribute), true);
            if (atts.Length > 0)
            {
                var att = ((CoreCmdAttribute)atts[0]);
                var api = new CoreCmdAction()
                {
                    Att = att,
                    Act = (Action<CmdInfo>)Delegate.CreateDelegate(typeof(Action<CmdInfo>), t, method),
                };
                DictCmdAction[api.Att.Cmd] = api;
            }
        }
    }
    public void Exec(CmdInfo cmd)
    {
        loger.Debug(Jsh.Jstr(cmd));
        if (DictCmdAction.TryGetValue(cmd.Cmd, out var api))
        {
            try
            {
                api.Act(cmd);
            }
            catch (Exception e)
            {
                loger.Warn($"处理指令：{cmd} {Jsh.Jstr(cmd)} 出错", e);
            }
        }
        else
        {
            loger.Warn($"无效指令：{cmd} {Jsh.Jstr(cmd)} 请输入 help 查看全部指令");
        }
    }
}